﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;

namespace BookStoreService.Core.Tools
{
    public class FilePersistence
    {
        static object o = new object();

        public static void Save<T>(List<T> list, string fileName)
        {
            lock (o)
            {
                string directoryName = Path.GetDirectoryName(fileName);
                if (directoryName == null)
                    throw new NullReferenceException(string.Format("File {0} path is invalid", fileName));

                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }
                using (var fs = new FileStream(fileName, FileMode.Create))
                {
                    var ser = new XmlSerializer(typeof(List<T>));
                    ser.Serialize(fs, list);
                    fs.Flush();
                    fs.Close();
                }
            }

        }
        public static List<T> Load<T>(string fileName)
        {
            //lock (o)
            //{
                if (!File.Exists(fileName))
                    throw new FileNotFoundException(fileName);

                List<T> result;

                using (var fs = new FileStream(fileName, FileMode.Open))
                {
                    var ser = new XmlSerializer(typeof (List<T>));
                    result = (List<T>) ser.Deserialize(fs);
                }
                return result;
            //}
        }

    }
}